//
//  APPLEEmoticonTools.swift
//  123
//
//  Created by pangjiaxing on 16/1/14.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
// 一页最大的列数与行数
let HMEmoticonKeyboardPageMaxCol = 7
let HMEmoticonKeyboardPageMaxRow = 3
// 一页显示的表情个数
let HMEmoticonKeyboardCountOfPage = HMEmoticonKeyboardPageMaxCol * HMEmoticonKeyboardPageMaxRow - 1
class APPLEEmoticonTools: NSObject {
    
    static let sharedTools : APPLEEmoticonTools = APPLEEmoticonTools()
    
    lazy var emoticonBundle : NSBundle = {
       let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        return NSBundle(path: path!)!
    }()
    
    private lazy var recentEmoticons:[APPLEEmoticon] = {
        return [APPLEEmoticon]()
    }()
    
    private lazy var defaultEmoticons:[APPLEEmoticon] = {
       return self.emoticonsWithPath("default/info.plist")
    }()
    
    private lazy var emojiEmoticons:[APPLEEmoticon] = {
        return self.emoticonsWithPath("emoji/info.plist")
    }()
    
    private lazy var lxhEmoticons:[APPLEEmoticon] = {
        return self.emoticonsWithPath("lxh/info.plist")
    }()
    
    lazy var allEmoticon : [[[APPLEEmoticon]]] = {
       return
        [
            self.emoticonsWithEmoticons(self.recentEmoticons),
            self.emoticonsWithEmoticons(self.defaultEmoticons),
            self.emoticonsWithEmoticons(self.emojiEmoticons),
            self.emoticonsWithEmoticons(self.lxhEmoticons)
            
        ]
    }()
    
    private func emoticonsWithEmoticons(emotions:[APPLEEmoticon])->([[APPLEEmoticon]]){
        let pageCount = (emotions.count - 1)/HMEmoticonKeyboardCountOfPage + 1
        var result :([[APPLEEmoticon]]) = [[APPLEEmoticon]]()
        for value in 0..<pageCount {
            
            let location = value*HMEmoticonKeyboardCountOfPage
            var length = HMEmoticonKeyboardCountOfPage
            if location+length > emotions.count{
                length = emotions.count-location
            }
            let range = NSMakeRange(location, length)
            let pageEmoticons = (emotions as NSArray).subarrayWithRange(range) as! [APPLEEmoticon]
            result.append(pageEmoticons)
            
        }
        return result
    }
    private func emoticonsWithPath(path:String)->([APPLEEmoticon]){
        let childPath = self.emoticonBundle.pathForResource(path, ofType: nil)
        let array = NSArray(contentsOfFile: childPath!)
        var result = [APPLEEmoticon]()
        for value in array!{
            let emoticon = APPLEEmoticon(dict: value as! [String:AnyObject])
            emoticon.path =  (path as NSString).stringByDeletingLastPathComponent
            print((path as NSString).stringByDeletingLastPathComponent)
            result.append(emoticon)
        }
        return result
    }
    
}
